package com.copa.gameStore.application.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.copa.gameStore.application.UserApplicationService;
import com.copa.gameStore.domain.User;
import com.copa.gameStore.domain.UserAccount;
import com.copa.gameStore.domain.UserRole;
import com.copa.gameStore.dto.UserDto;
import com.copa.gameStore.mapper.UserAccountMapper;
import com.copa.gameStore.mapper.UserRoleMapper;
import com.copa.gameStore.service.UserAccountService;
import com.copa.gameStore.service.UserRoleService;
import com.copa.gameStore.service.UserService;
import com.copa.gameStore.vo.ResponseVo;
import com.copa.gameStore.vo.UserVo;
import com.nimbusds.jose.JWSObject;
import org.springframework.beans.BeanUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Enumeration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.copa.gameStore.enums.Role.ROLE_USER;

/**
 * @author copa
 * @createDate 2022-10-20 16:49
 * @function
 */
@Service
public class UserApplicationServiceImpl implements UserApplicationService {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private UserService userService;

    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private UserAccountService userAccountService;

    @Override
    public List<String> roleNameByUserId(Long userId) {
        return userRoleMapper.listRoleName(userId);
    }

    @Override
    public User findByUsername(String username) {
        return userService.findByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVo<User> register(UserDto userDto) {
        User user = userService.register(userDto);
        UserRole userRole = new UserRole().setUserId(user.getId()).setRoleId(ROLE_USER.getRoleId());
        userRoleService.add(userRole);
        UserAccount userAccount = new UserAccount().setUserId(user.getId()).setAccount(new BigDecimal(0));
        userAccountService.add(userAccount);
        return ResponseVo.successMsg("注册成功~");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseVo<String> put(UserDto userDto) {
        if (get().getData().getId() != userDto.getId()) {
            throw new ValidationException("非法操作！");
        }
        userService.put(userDto);
        return ResponseVo.successMsg("修改信息成功~");
    }

    @Override
    public UserVo userInfo(String authorization) {
        return get().getData();
    }

    @Override
    public ResponseVo<UserAccount> account() {
        UserVo user = get().getData();
        return ResponseVo.success(userAccountMapper.selectOne(new QueryWrapper<UserAccount>().eq("user_id", user.getId())));
    }

    @Override
    public void takeAccount(BigDecimal money, UserAccount account) {
        userAccountService.takeAccount(money, Objects.isNull(account) ? account().getData() : account);
    }

    @Override
    public UserAccount accountByUserId(Long userId) {
        return Optional.ofNullable(userAccountMapper.selectOne(
                        new QueryWrapper<UserAccount>().eq("user_id", userId)))
                .orElseThrow(() -> new ValidationException("非法操作~"));
    }

    @Override
    public ResponseVo<String> resetPassword(String username) {
        userService.resetPassword(username);
        return ResponseVo.success("重置密码成功~");
    }

    @Override
    public ResponseVo<String> recharge(String username, BigDecimal money) {
        User user = userService.findByUsername(username);
        userAccountService.recharge(user.getId(), money);
        return ResponseVo.success("充值成功~");
    }

    @Override
    public ResponseVo<UserVo> get() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String userJson = request.getHeader("user");
        if (Objects.nonNull(userJson)) {
            JSONObject userJsonObject = new JSONObject(userJson);
            User user = userService.findByUsername(userJsonObject.getStr("username"));
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            userVo.setAuthorities(Convert.toList(String.class, userJsonObject.get("authorities")));
            return ResponseVo.success(userVo);

        }
        return ResponseVo.error();
    }

    @Override
    public ResponseVo<User> getUser(Long id) {
        return ResponseVo.success(userService.findById(id));
    }
}
